Search for a Range

Given a sorted array of integers, find the starting and ending position of a given target value.

Your algorithm’s runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

For example,

Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

Solution:

  1. public class Solution {
  2. public int[] searchRange(int[] nums, int target) {
  3. int lo = lower(nums, target, 0, nums.length - 1);
  4. if (lo == -1) {
  5. return new int[] {-1, -1};
  6. }
  7. int hi = upper(nums, target, 0, nums.length - 1);
  8. return new int[] {lo, hi};
  9. }
  10. int lower(int[] nums, int target, int lo, int hi) {
  11. if (lo > hi) {
  12. return -1;
  13. }
  14. int mid = lo + (hi - lo) / 2;
  15. if (nums[mid] == target && (mid == 0 || nums[mid - 1] < target)) {
  16. return mid;
  17. }
  18. if (nums[mid] >= target) {
  19. return lower(nums, target, lo, mid - 1);
  20. } else {
  21. return lower(nums, target, mid + 1, hi);
  22. }
  23. }
  24. int upper(int[] nums, int target, int lo, int hi) {
  25. if (lo > hi) {
  26. return -1;
  27. }
  28. int mid = lo + (hi - lo) / 2;
  29. if (nums[mid] == target && (mid == nums.length - 1 || target < nums[mid + 1])) {
  30. return mid;
  31. }
  32. if (nums[mid] <= target) {
  33. return upper(nums, target, mid + 1, hi);
  34. } else {
  35. return upper(nums, target, lo, mid - 1);
  36. }
  37. }
  38. }